# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from Persimmon import settings
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
from movie.models import Movie, Comment, Stamp
from django.utils.encoding import python_2_unicode_compatible
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer


@python_2_unicode_compatible
class User(AbstractUser):
	# through:通过中间表联系
	movies = models.ManyToManyField(Movie, related_name='movies', through=Comment, through_fields=('user', 'movie'),
	                                null=True, blank=True)
	telephone = models.CharField(max_length=20, blank=True, null=True)
	avatar = models.ImageField(blank=True, null=True, upload_to='upload/avatar')  # 路径：MEDIA_ROOT之后
	nick_name = models.CharField(max_length=20, blank=True, null=True)
	about_me = models.CharField(max_length=50, null=True, blank=True)
	gender = models.CharField(max_length=10, choices=(("male", "男"), ("female", "女")))
	role = models.IntegerField(default=0)
	# 心愿单需求
	stamps = models.ManyToManyField(Movie, related_name='stamps', through=Stamp, through_fields=('user', 'movie'),
	                                null=True, blank=True)

	class Meta(object):
		verbose_name = "用户"
		unique_together = (('username', 'email'),)

	def __str__(self):
		return self.username

	def visit_stamp(self, movie_id):
		stamp = Stamp.objects.filter(user_id=self.id, movie_id=movie_id)
		return stamp

	def generate_confirm_token(self, expiration=3600):
		s = Serializer(secret_key=settings.SECRET_KEY, expires_in=expiration)
		return s.dumps({'confirm': self.id})

	def confirm(self, token):
		s = Serializer(secret_key=settings.SECRET_KEY)
		try:
			print(token)
			data = s.loads(token)
			print(data)
		except:
			return False
		if data.get('confirm') != self.id:
			print('here')
			return False
		self.is_active = True
		self.save()
		return True


